package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2023/4/7
 *
 *  滚动聚合: 效率高。
 *     reduce
 *     窗口中每加入一个元素，聚合就执行一次。
 *
 *     限制：聚合的输入和输出必须是同一种类型。
 *
 *
 */
public class Demo6_Reduce
{
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .countWindow(5)
                   .reduce(new ReduceFunction<WaterSensor>()
                   {
                       /*
                        输出最新数据的其他列，和聚合列
                        WaterSensor value1： 之前聚合的结果
                        WaterSensor value2： 当前进入窗口的数据
                        */
                       @Override
                       public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                           System.out.println("Demo6_Reduce.reduce");
                          value2.setVc( value2.getVc() + value1.getVc()) ;
                       return value2;
                       }
                   })
                   .print();

                env.execute();


    }
}
